﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.IRepository.IService;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.Models.PDA;
using DFGK_WMS.Repository.Service;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;
using NetTaste;
using NPOI.POIFS.Crypt.Dsig;
using Org.BouncyCastle.Asn1.X509;
using SqlSugar;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static DFGK_WMS.Model.DTO.ShelvesSinles;

namespace DFGK_WMS.Repository
{
    public class TReceivingBillRepository : BaseRepository<Model.Models.TReceivingBill>, ITReceivingBillRepository
    {
        public IBarCodeRuleRepository BarCodeRuleRepository { get; }
        public ITReceivingOrderDetailRepository TReceivingOrderDetail { get; }
        public IStackingStorageService StackingStorageService { get; }
        public ITLogRepository TLogRepository { get; }

        private readonly IBarCodeRuleRepository _BarCodeRuleRepositoy;


        public TReceivingBillRepository(DFGK_DB context,
            IMapper mapper, IBarCodeRuleRepository barCodeRuleRepository,
            ITReceivingOrderDetailRepository tReceivingOrderDetail,
            IStackingStorageService stackingStorageService,
            ITLogRepository tLogRepository,
             IBarCodeRuleRepository barCodeRuleRepositoy) : base(context, mapper)
        {
            BarCodeRuleRepository = barCodeRuleRepository;
            TReceivingOrderDetail = tReceivingOrderDetail;
            StackingStorageService = stackingStorageService;
            TLogRepository = tLogRepository;
            _BarCodeRuleRepositoy = barCodeRuleRepositoy;

        }

        /// <summary>
        /// 逻辑分区
        /// </summary>
        /// <returns></returns>
        public List<TDictItem> GetDictItems()
        {
            var list = Context.TDictItems
                .Where(x => x.TypeId == 41);

            if (list == null)
            {
                return null;
            }

            return list.ToList();
        }

        /// <summary>
        /// 添加收货单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddReceivingBill(Model.Models.TReceivingBill m, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    message = "";
                    var cuobj = Context.TCustomers.FirstOrDefault(s => s.Id == m.CustomerId);
                    if (cuobj != null)
                    {
                        m.CustomerName = cuobj.Name;
                    }
                    else
                    {
                        message = "客户不存在或者已被禁用！客户名称：" + m.CustomerName;
                        tran.Rollback();
                        return false;
                    }
                    //供应商信息
                    var sobj = Context.TSuppliers.FirstOrDefault(s => s.Id == m.SupplierId);
                    if (sobj != null)
                    {
                        m.SupplierName = sobj.Name;
                    }
                    else
                    {
                        message = "供应商不存在或者已被禁用！";
                        tran.Rollback();
                        return false;
                    }
                    var Exists = Context.TReceivingBills.FirstOrDefault(r => r.BillNo == m.BillNo);
                    if (Exists is not null || Exists != null)
                    {
                        message = "收货单号已存在！单号为：" + Exists.BillNo;
                        tran.Rollback();
                        return false;
                    }
                    //仓库信息
                    var wobj = Context.TWarehouses.Find(m.WarehouseId);
                    if (wobj != null && wobj.Status == 1)
                    {
                        m.WarehouseName = wobj.Name;
                        m.WarehouseCode = wobj.Code;
                    }
                    else
                    {
                        message = "库房不存在或已被禁用！";
                        tran.Rollback();
                        return false;
                    }

                    //初始化状态
                    m.Status = 0;
                    //默认收货数量
                    m.ReceivedQTY = 0;
                    m.BeginDate = DateTime.Now;

                    #region 审计字段
                    m.CreateUserId = m.NowUserId;
                    m.CreateUserName = m.NowUserRealName;
                    m.CreateDate = DateTime.Now;
                    Context.TReceivingBills.Add(m);
                    Context.SaveChanges();
                    #endregion
                    foreach (var item in m.BillDetailList)
                    {
                        if (item.Qty <= 0)
                        {
                            message = "收货数量不能小于0";
                            tran.Rollback();
                            return false;
                        }
                        if (item.Qty % 1 != 0)
                        {
                            message = "收货数量包含小数";
                            tran.Rollback();
                            return false;
                        }
                        item.BatchNo = new string(item.BatchNo.Select(c => Char.IsLower(c) ? Char.ToUpper(c) : c).ToArray());
                        //if (!JudgmentBatchNo(item.BatchNo,out message))
                        //{
                        //    message = item.MaterialName+ "物料的" + message;
                        //    tran.Rollback();
                        //    return false;
                        //}
                        var sub = Context.TOwners.FirstOrDefault(o => o.Status == 0 && o.Id == item.OwnerId);
                        if (sub is not null)
                        {
                            message = item.OwnerName + ",货主不存在或已被禁用";
                            tran.Rollback();
                            return false;
                        }
                        //供应商
                        item.SupplierId = m.SupplierId;
                        item.SupplierName = m.SupplierName;

                        //item.OrderSn = _BarCodeRuleRepositoy.GetBarCodeSample(1);

                        //关联单号
                        item.BillNo = m.BillNo;
                        item.BillId = m.Id;
                        //初始化状态
                        item.Status = 0;
                        //创建日期
                        item.CreateDate = DateTime.Now;
                        Context.TReceivingBillDetails.Add(item);
                    }
                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    tran.Rollback();
                    return false;
                    throw;
                }
            }
        }
        /// <summary>
        /// 判断批次号格式
        /// </summary>
        /// <param name="BatchNo"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool JudgmentBatchNo(string BatchNo, out string message)
        {
            message = "";
            if (BatchNo.Length != 10 || !char.IsLetter(BatchNo[0]) || !char.IsLetter(BatchNo[1]) || !char.IsLetter(BatchNo[4]) || !char.IsLetter(BatchNo[7]))
            {
                message = "批次格式不正确,批次为：" + BatchNo;
                return false;
            }
            return true;
        }

        /// <summary>
        /// 收货入库(弃用)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddReceivingOrderDateil(ReceivingBillOrderDto m, out string message)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
                try
                {
                    var receivingBills = Context.TReceivingBills.FirstOrDefault(r => r.Id == m.Id);
                    if (receivingBills == null)
                    {
                        message = "收货单不存在";
                        return false;
                    }
                    decimal count = 0;
                    foreach (var item in m.ReceivingBillOrderDetailDtos)
                    {
                        if (item.ReceivedQty < 0)
                        {
                            message = "收货数量不能小于0";
                            return false;
                        }
                        var r = Context.TReceivingBillDetails.Find(item.ReceivingBillDetailId);
                        if (r is null)
                        {
                            message = "收货单明细不存在";
                            return false;
                        }
                        else
                        {
                            if (r.Qty >= item.ReceivedQty && (r.ReceivedQty + item.ReceivedQty) <= r.Qty)
                            {
                                r.ReceivedQty += item.ReceivedQty;
                                count += r.ReceivedQty;
                                if (r.Price is not null || r.Price >= 0)
                                {
                                    receivingBills.TotalPrice += (decimal)r.Price * item.ReceivedQty;
                                }
                            }
                            else
                            {
                                message = "收货数量不能大于物料数量";
                                return false;
                            }
                            Context.TReceivingBillDetails.Update(r);
                            //Context.SaveChanges();
                        }
                    }
                    string receordercode = BarCodeRuleRepository.GetBarCodeSample(1);
                    if (string.IsNullOrEmpty(receordercode) || receordercode.Length == 0)
                    {
                        //trans.Rollback();
                        message = "入库单编码不存在或已被禁用！";
                        return false;
                    }
                    bool reresult = false;
                    if (count == receivingBills.TotalQty)
                    {
                        receivingBills.Status = 2;
                        receivingBills.EndDate = DateTime.Now;
                        foreach (var item in m.ReceivingBillOrderDetailDtos)
                        {
                            if (item.ReceivedQty == 0)
                            {
                                continue;
                            }
                            TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                            receivingOrder.OrderSn = receordercode;
                            //本地入库
                            receivingOrder.BillType = 1;
                            receivingOrder.WarehouseId = m.Wid;
                            //receivingOrder.SupplierId = m.Suppid;
                            receivingOrder.MaterialId = item.MaterialId;
                            receivingOrder.OwnerId = item.OwerId;
                            receivingOrder.BatchNo = item.MaterialBatchNo;
                            //订单来源默认手动创建
                            receivingOrder.SourceType = 0;
                            //质检状态默认为合格
                            receivingOrder.QualityState = 1;
                            //质量状态
                            receivingOrder.Status = 3;
                            receivingOrder.ReceivedQty = 0;
                            receivingOrder.PackagedQty = 0;
                            receivingOrder.PackQty = 0;
                            receivingOrder.BatchNoExplain = item.BatchNoExplain;
                            receivingOrder.OutFactoryDate = item.OutFactoryDate;
                            receivingOrder.ProduceFactory = item.ProduceFactory;
                            receivingOrder.ProductDate = item.ProductDate;
                            receivingOrder.ExpireDate = item.ExpireDate;
                            receivingOrder.Remark = item.Remark;
                            receivingOrder.Qty = item.ReceivedQty;
                            #region 审计字段
                            receivingOrder.CreateUserId = m.NowUserId;
                            receivingOrder.CreateUserName = m.NowUserRealName;
                            receivingOrder.CreateDate = DateTime.Now;
                            //receivingOrder.ModifyUserId = m.NowUserId;
                            //receivingOrder.ModifyUserName = m.NowUserRealName;
                            //receivingOrder.ModifyDate = DateTime.Now;
                            receivingOrder.AuditUserId = m.NowUserId;
                            receivingOrder.AuditUserName = m.NowUserRealName;
                            receivingOrder.AuditDate = DateTime.Now;
                            receivingOrder.SubmitUserId = m.NowUserId;
                            receivingOrder.SubmitUserName = m.NowUserRealName;
                            receivingOrder.SubmitDate = DateTime.Now;
                            //采购订单行项目类型
                            receivingOrder.PurOrderLineType = 0;
                            receivingOrder.StackedQty = 0;
                            reresult = AddTReceivingOrderDetail(receivingOrder, out message);
                            #endregion
                        }
                        if (reresult == false)
                        {
                            tran.Rollback();
                            return false;
                        }
                        Context.TReceivingBills.Update(receivingBills);
                        //Context.SaveChanges();
                    }
                    if (count < receivingBills.TotalQty)
                    {
                        receivingBills.Status = 1;
                        #region 
                        foreach (var item in m.ReceivingBillOrderDetailDtos)
                        {
                            if (item.ReceivedQty == 0)
                            {
                                continue;
                            }
                            TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                            receivingOrder.OrderSn = receordercode;
                            //本地入库
                            receivingOrder.BillType = 1;
                            receivingOrder.WarehouseId = m.Wid;
                            receivingOrder.SupplierId = m.Suppid;
                            receivingOrder.MaterialId = item.MaterialId;
                            receivingOrder.OwnerId = item.OwerId;
                            receivingOrder.BatchNo = item.MaterialBatchNo;
                            //订单来源默认手动创建
                            receivingOrder.SourceType = 0;
                            //质检状态默认为合格
                            receivingOrder.QualityState = 1;
                            //质量状态
                            receivingOrder.Status = 3;
                            receivingOrder.ReceivedQty = 0;
                            receivingOrder.PackagedQty = 0;
                            receivingOrder.PackQty = 0;
                            receivingOrder.BatchNoExplain = item.BatchNoExplain;
                            receivingOrder.OutFactoryDate = item.OutFactoryDate;
                            receivingOrder.ProduceFactory = item.ProduceFactory;
                            receivingOrder.ProductDate = item.ProductDate;
                            receivingOrder.ExpireDate = item.ExpireDate;
                            receivingOrder.Remark = item.Remark;
                            receivingOrder.Qty = item.ReceivedQty;
                            #region 审计字段
                            receivingOrder.CreateUserId = m.NowUserId;
                            receivingOrder.CreateUserName = m.NowUserRealName;
                            receivingOrder.CreateDate = DateTime.Now;
                            //receivingOrder.ModifyUserId = m.NowUserId;
                            //receivingOrder.ModifyUserName = m.NowUserRealName;
                            //receivingOrder.ModifyDate = DateTime.Now;
                            receivingOrder.AuditUserId = m.NowUserId;
                            receivingOrder.AuditUserName = m.NowUserRealName;
                            receivingOrder.AuditDate = DateTime.Now;
                            receivingOrder.SubmitUserId = m.NowUserId;
                            receivingOrder.SubmitUserName = m.NowUserRealName;
                            receivingOrder.SubmitDate = DateTime.Now;
                            //采购订单行项目类型
                            receivingOrder.PurOrderLineType = 0;
                            receivingOrder.StackedQty = 0;
                            reresult = AddTReceivingOrderDetail(receivingOrder, out message);
                            #endregion
                        }
                        if (reresult == false)
                        {
                            tran.Rollback();
                            return false;
                        }
                        #endregion
                        Context.TReceivingBills.Update(receivingBills);
                    }
                    Context.SaveChanges();
                    //提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }

        }


        /// <summary>
        /// PC/PDA收货入库
        /// </summary>
        /// <param name="receivingBillOrderDto"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddPDAReceivingOrderDateil(ReceivingBillOrderDto m, out string message, ref List<TCell> Getcell)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
                try
                {
                    var receivingBills = Context.TReceivingBills.FirstOrDefault(r => r.Id == m.Id);
                    if (receivingBills == null)
                    {
                        message = "收货单不存在";
                        return false;
                    }
                    var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == receivingBills.Id).ToList();

                    foreach (var item in rbd)
                    {
                        if (item.ReceivedQty <= 0)
                        {
                            continue;
                        }
                        receivingBills.ReceivedQTY = receivingBills.ReceivedQTY.GetValueOrDefault() + item.ReceivedQty;
                    }
                    string receordercode = "";

                    //查看收货单已收货数量是否是0 （是的话创建一个入库单编号 不是0查询出入库单编号）
                    if (receivingBills.ReceivedQTY == 0 || receivingBills.ReceivedQTY is null)
                    {
                        receordercode = BarCodeRuleRepository.GetBarCodeSample(1);
                        if (string.IsNullOrEmpty(receordercode) || receordercode.Length == 0)
                        {
                            //trans.Rollback();
                            message = "入库单编码不存在或已被禁用！";
                            tran.Rollback();
                            return false;
                        }
                    }
                    else
                    {
                        var rece = Context.TReceivingOrderDetails.AsNoTracking().FirstOrDefault(r => r.ReceivingBillId == receivingBills.Id);
                        if (rece is null)
                        {
                            message = "入库单编码不存在！";
                            tran.Rollback();
                            return false;
                        }
                        receordercode = rece.OrderSn;
                    }

                    decimal count = 0;//计算数量
                    foreach (var item in m.ReceivingBillOrderDetailDtos)
                    {
                        if (item.ReceivedQty < 0)
                        {
                            message = "收货数量不能小于0";
                            tran.Rollback();
                            return false;
                        }
                        if (item.ReceivedQty % 1 != 0)
                        {
                            message = "收货数量包含小数";
                            tran.Rollback();
                            return false;
                        }
                        var r = Context.TReceivingBillDetails.Find(item.ReceivingBillDetailId);
                        if (r is null)
                        {
                            message = "收货单明细不存在";
                            tran.Rollback();
                            return false;
                        }
                        else
                        {
                            if (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode) || item.MaterialBatchNo is null || string.IsNullOrEmpty(item.MaterialBatchNo))
                            {
                                continue;
                            }
                            if (r.Qty >= item.ReceivedQty && (r.ReceivedQty + item.ReceivedQty) <= r.Qty)
                            {
                                r.ReceivedQty += item.ReceivedQty;
                                count += item.ReceivedQty;
                                if (r.Price is not null || r.Price >= 0)
                                {
                                    receivingBills.TotalPrice += (decimal)r.Price * item.ReceivedQty;
                                }
                            }
                            else
                            {
                                message = "收货数量不能大于物料数量";
                                tran.Rollback();
                                return false;
                            }
                            Context.TReceivingBillDetails.Update(r);
                            Context.SaveChanges();




                        }
                        var palletbarList = Context.TPallets.Where(x => x.PalletBarcode == item.PalletBarcode);
                        if (palletbarList.Count() <= 0)
                        {
                            message = "未查询到此托盘" + item.PalletBarcode;
                            tran.Rollback();
                            return false;
                        }
                        var palletBarListUpd = palletbarList.First();
                        palletBarListUpd.LoadFactor = item.LoadFactor;
                        Context.TPallets.Update(palletBarListUpd);
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "更新托盘表失败";
                            tran.Rollback();
                            return false;
                        }
                    }
                    var res = Context.TReceivingBillDetails.Where(x => x.BillId == receivingBills.Id).ToList();
                    bool reresult = false;
                    foreach (var item in rbd)
                    {
                        count += item.ReceivedQty;
                    }
                    if (count == receivingBills.TotalQty)
                    {
                        reresult = AddReceivingOrderDeatils(m, receordercode, out message, ref Getcell);
                        if (!reresult)
                        {
                            message = message;
                            tran.Rollback();
                            return false;
                        }
                        receivingBills.Status = 2;
                        receivingBills.EndDate = DateTime.Now;
                        Context.TReceivingBills.Update(receivingBills);
                        Context.SaveChanges();
                    }
                    if (count < receivingBills.TotalQty)
                    {
                        reresult = AddReceivingOrderDeatils(m, receordercode, out message, ref Getcell);
                        if (!reresult)
                        {
                            message = message;
                            tran.Rollback();
                            return false;
                        }
                        receivingBills.Status = 1;
                        Context.TReceivingBills.Update(receivingBills);
                        Context.SaveChanges();
                    }
                    Context.SaveChanges();
                    //提交事务
                    message = "收货成功";
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    TLogRepository.Add(new TLog()
                    {
                        ActionType = 0,
                        CreateDate = DateTime.Now,
                        Description = message,
                        LogType = 1,
                        UserName = m.NowUserRealName
                    });
                    tran.Rollback();
                    return false;
                    throw;
                }
        }

        public bool AddTPutawayOrderDetail(ReceivingBillOrderDto m)
        {
            TPutawayOrder putawayOrder = new TPutawayOrder();
            List<TReceivingBillDetail> receivingBillList = null;
            List<TStackingStorage> stackingStoragesList = null;
            foreach (var item in m.ReceivingBillOrderDetailDtos)
            {
                receivingBillList = Context.TReceivingBillDetails.Where(x => x.Id == item.ReceivingBillDetailId).ToList();
                stackingStoragesList = Context.TStackingStorages.Where(x => x.PalletBarcode == item.PalletBarcode && x.Status == 1).ToList();

                putawayOrder.PalletBarcode = item.PalletBarcode;
                putawayOrder.ParentPalletBarcode = item.PalletBarcode;
            }
            foreach (var receivingBill in receivingBillList)
            {
                //添加上架单
                {
                    putawayOrder.Code = DateTime.Now.ToString("yyyyMMddHHmmss");
                    putawayOrder.RelatedOrderDetailId = receivingBill.Id;
                    putawayOrder.StackingStorageId = stackingStoragesList.First().Id;

                    putawayOrder.LocationCode = stackingStoragesList.First().ExpectedLocation;
                    putawayOrder.Status = 4;
                    putawayOrder.Qty = stackingStoragesList.First().Qty;
                    putawayOrder.CreateDate = DateTime.Now;
                    putawayOrder.MaterialId = receivingBill.MaterialId;
                    putawayOrder.MaterialCode = receivingBill.MaterialCode;
                    putawayOrder.MaterialName = receivingBill.MaterialName;
                    putawayOrder.BatchNo = receivingBill.BatchNo;
                    putawayOrder.OwnerId = receivingBill.OwnerId;
                    putawayOrder.OwnerName = receivingBill.OwnerName;
                    putawayOrder.CreateUserId = 0;
                    putawayOrder.CreateUserName = "系统";
                    putawayOrder.SourceType = 1;
                    putawayOrder.TotalWeight = receivingBill.Weight;
                };


                var isok = Context.TPutawayOrders.Add(putawayOrder);
                if (Context.SaveChanges() <= 0)
                {
                    return false;
                }

                var putawayList = Context.TPutawayOrders.First(x => x.Code == putawayOrder.Code);
                //添加上架单明细
                TPutawayOrderDetail putawayOrderDetail = new TPutawayOrderDetail()
                {
                    PutawayOrderId = putawayList.Id,
                    PalletBarcode = putawayList.PalletBarcode,
                    PackageBarcode = putawayList.PalletBarcode,
                    MaterialBarcode = putawayList.MaterialCode,
                };
                var putIsOk = Context.TPutawayOrderDetails.Add(putawayOrderDetail);
                if (Context.SaveChanges() <= 0)
                {
                    return false;
                }

            }
            return true;


        }

        /// <summary>
        /// 查询上架单
        /// </summary>
        /// <param name="palletBarCode"></param>
        /// <returns></returns>
        public TPutawayOrder GetPutawayOrder(string palletBarCode)
        {
            var putawayOrder = Context.TPutawayOrders.Where(x => x.PalletBarcode == palletBarCode && x.Status == 4).OrderByDescending(x => x.CreateDate).FirstOrDefault();
            return putawayOrder;
        }


        #region 封装方法收货入库
        /// <summary>
        /// 添加入库单管理
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTReceivingOrderDetail(TReceivingOrderDetail m, out string message)
        {
            message = "";

            //货主信息
            if (m.OwnerId.HasValue)
            {
                //var depobj = Context.TDepartments.AsQueryable();
                //var depowobj = Context.TDepartmentOwners.Where(x => x.OwnerId == m.OwnerId);
                //var owobj = Context.TOwners.Where(x=>x.Status==1);
                //var delist = (from d in depobj
                //              join de in depowobj
                //              on d.Id equals de.DepartmentId
                //              join o in owobj
                //              on de.OwnerId equals o.Id
                //              select d).FirstOrDefault();
                //if (delist != null)
                //{
                //    m.DeptCode = delist.DepartmentCode;
                //    m.DeptName = delist.DepartmentName;
                //    var owerobj = owobj.Where(x => x.Id == m.OwnerId).FirstOrDefault();
                //    if (owerobj != null)
                //    {
                //        m.OwnerName = owerobj.Name;
                //    }
                //}
                //else
                //{
                //    message = "货主不存在，或已被禁用，请先维护";
                //    return false;
                //}
                //var cusobj = Context.TCustomers.AsNoTracking().FirstOrDefault(r => r.Id == m.CustomerId && r.MengNiuStatus == true);
                //if (cusobj != null)
                //{
                //    m.CustomerName = cusobj.Name;
                //}
                //else
                //{
                //    message = "客户不存在，或已被禁用，请先维护";
                //    return false;
                //}

                var owobj = Context.TOwners.Where(x => x.Status == 1);
                var owerobj = owobj.Where(x => x.Id == m.OwnerId).FirstOrDefault();
                if (owerobj != null)
                {
                    if (owerobj != null)
                    {
                        m.OwnerName = owerobj.Name;
                    }
                }
                else
                {
                    message = "货主不存在，或已被禁用，请先维护";
                    return false;
                }
            }
            else
            {
                m.OwnerId = 0;
                m.OwnerName = "";
                m.DeptCode = "";
                m.DeptName = "";
            }

            //库房信息
            var warehouseobj = Context.TWarehouses.Find(m.WarehouseId);
            if (warehouseobj != null && warehouseobj.Status == 1)
            {
                m.WarehouseName = warehouseobj.Name;
                m.WarehouseCode = warehouseobj.Code;
            }
            else
            {
                message = "仓库不存在或仓库已被禁用，请先维护";
                return false;
            }
            //供应商信息
            var supplierobj = Context.TSuppliers.Find(m.SupplierId);
            if (supplierobj != null)
            {
                m.SupplierName = supplierobj.Name;
            }
            //物料信息
            var materialobj = Context.TMaterials.Find(m.MaterialId);
            if (materialobj != null)
            {
                m.MaterialCode = materialobj.Code;
                m.MaterialImg = materialobj.Img;
                m.MaterialName = materialobj.Name;
                m.UnitId = materialobj.UnitId;
                m.UnitName = materialobj.UnitName;
                m.MaterialTypeCode = materialobj.TypeCode;
                m.MaterialTypeName = materialobj.TypeName;
                if (materialobj.ExpirationMonth.HasValue && m.ProductDate.HasValue)
                {
                    m.ExpireDate = m.ProductDate.Value.AddMonths(materialobj.ExpirationMonth.Value);
                }
            }
            //物料批次
            TMaterialKey materialKey = null;
            var materkeyobj = Context.TMaterialKeys.FirstOrDefault(x => x.BatchNo == m.BatchNo && x.MaterialId == m.MaterialId);
            if (materkeyobj != null)
            {
                materialKey = materkeyobj;
            }
            //逻辑分区
            var dicobj = Context.TDictItems.FirstOrDefault(x => x.ItemCode == m.LogicalPartCode);
            if (dicobj != null)
            {
                m.LogicalPartName = dicobj.ItemName;
            }
            //订单来源默认手动创建
            m.SourceType = 0;
            //质检状态默认为合格
            m.QualityState = 1;
            m.ReceivedQty = 0;
            m.PackagedQty = 0;
            m.PackQty = 0;

            //采购订单行项目类型
            m.PurOrderLineType = 0;
            m.StackedQty = 0;
            if (materialKey == null)
            {
                TMaterialKey materkeyinsert = new TMaterialKey();
                materkeyinsert.BatchNo = m.BatchNo;
                materkeyinsert.MaterialId = m.MaterialId;
                materkeyinsert.OutFactoryDate = m.OutFactoryDate;
                materkeyinsert.OwnerId = m.OwnerId;
                materkeyinsert.OwnerName = m.OwnerName;
                materkeyinsert.ProduceFactory = m.ProduceFactory;
                materkeyinsert.ProductDate = m.ProductDate;
                materkeyinsert.Qadate = m.Qadate;
                materkeyinsert.SupplierName = m.SupplierName;
                materkeyinsert.SupplierId = m.SupplierId;
                materkeyinsert.ExpireDate = m.ExpireDate;
                materkeyinsert.CreateDate = DateTime.Now;
                materkeyinsert.MaterialCode = m.MaterialCode;
                materkeyinsert.MaterialName = m.MaterialName;
                materkeyinsert.QualityState = m.QualityState;
                materkeyinsert.DeptCode = m.DeptCode;
                materkeyinsert.DeptName = m.DeptName;
                materkeyinsert.Mblnr = m.Mblnr;
                materkeyinsert.Mjahr = m.Mjahr;
                materkeyinsert.Zeile = m.Zeile;
                materkeyinsert.ContractNo = m.ContractNo;
                materkeyinsert.PurOrderNo = m.PurOrderNo;
                materkeyinsert.PurOrderLineNo = m.PurOrderLineNo;
                materkeyinsert.PurOrderLineType = m.PurOrderLineType;
                materkeyinsert.ProOrderNo = m.ProOrderNo;
                materkeyinsert.OutOrderNo = m.OutOrderNo;
                Context.TMaterialKeys.Add(materkeyinsert);
                int result = Context.SaveChanges();
                if (result == 0)
                {
                    message = "保存失败！";

                    return false;
                }
                m.MaterialKeyId = materkeyinsert.Id;
            }
            else
            {
                m.MaterialKeyId = materialKey.Id;
                var materkey = Context.TMaterialKeys.Find(m.MaterialKeyId);
                if (materkey != null)
                {
                    materkey.BatchNo = m.BatchNo;
                    materkey.OutFactoryDate = m.OutFactoryDate;
                    materkey.OwnerId = m.OwnerId;
                    materkey.OwnerName = m.OwnerName;
                    materkey.ProduceFactory = m.ProduceFactory;
                    materkey.ProductDate = m.ProductDate;
                    materkey.Qadate = m.Qadate;
                    materkey.SupplierId = m.SupplierId;
                    materkey.SupplierName = m.SupplierName;
                    materkey.ExpireDate = m.ExpireDate;
                    materkey.MaterialCode = m.MaterialCode;
                    materkey.MaterialName = m.MaterialName;
                    materkey.QualityState = m.QualityState;
                    materkey.DeptCode = m.DeptCode;
                    materkey.DeptName = m.DeptName;
                    materkey.Mblnr = m.Mblnr;
                    materkey.Mjahr = m.Mjahr;
                    materkey.Zeile = m.Zeile;
                    materkey.ContractNo = m.ContractNo;
                    materkey.ProOrderNo = m.ProOrderNo;
                    materkey.PurOrderLineNo = m.PurOrderLineNo;
                    materkey.PurOrderLineType = m.PurOrderLineType;
                    materkey.ProOrderNo = m.ProOrderNo;
                    materkey.OutOrderNo = m.OutOrderNo;
                    Context.TMaterialKeys.Update(materkey);
                }
                int result = Context.SaveChanges();
                if (result <= 0)
                {
                    message = "保存失败！";

                    return false;
                }
            }
            Context.TReceivingOrderDetails.Add(m);
            int resultt = Context.SaveChanges();
            if (resultt > 0)
            {

                return true;
            }
            return false;
        }
        #endregion

        /// <summary>
        /// 强制完成
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool ReceivingBillComplete(int id)
        {
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    var res = Context.TReceivingBills.FirstOrDefault(b => b.Id == id);
                    res.Status = 2;
                    res.EndDate = DateTime.Now;
                    Context.TReceivingBills.Update(res);
                    Context.SaveChanges();

                    var receivingBillDetails = Context.TReceivingBillDetails.Where(r => r.BillId == id).ToList();
                    foreach (var item in receivingBillDetails)
                    {
                        item.Status = 1;
                        Context.TReceivingBillDetails.Update(item);
                        Context.SaveChanges();
                    }
                    Context.SaveChanges();
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 删除收货单
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelReceivingBill(int rid, out string message)
        {
            try
            {
                message = "";
                var robj = Context.TReceivingBills.Find(rid);
                if (robj != null)
                {
                    if (robj.Status == 1 || robj.Status == 2)
                    {
                        return false;
                    }
                    Context.TReceivingBills.Remove(robj);
                    Context.SaveChanges();
                    message = "添加成功!";
                    return true;
                }
                message = "添加失败!";
                return false;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return false;
                throw;
            }

        }

        /// <summary>
        /// 收获管理显示
        /// </summary>
        /// <param name="supplierId"></param>
        /// <param name="status"></param>
        /// <param name="warehouseId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Model.Models.TReceivingBill> GetReceivingBillList(int supplierId, int? status, int warehouseId, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TReceivingBills.AsNoTracking().ToList();
            foreach (var item in list)
            {
                var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == item.Id);

                foreach (var item2 in rbd)
                {
                    if (item2.ReceivedQty <= 0)
                    {
                        continue;
                    }
                    item.ReceivedQTY = item.ReceivedQTY.GetValueOrDefault() + item2.ReceivedQty;
                }
            }
            //查找供应商
            if (supplierId != 0)
            {
                list = list.Where(x => x.SupplierId == supplierId).ToList();
            }
            //查询状态
            if (status is not null && status != 3)
            {
                list = list.Where(x => x.Status == status).ToList();
            }

            if (status is not null && status == 3)
            {
                list = list.Where(x => x.Status != 2).ToList();
            }


            //查找库房
            if (warehouseId != 0)
            {
                list = list.Where(x => x.WarehouseId == warehouseId).ToList();
            }
            totalCount = list.Count();
            list = list.OrderByDescending(x => x.CreateDate).ToList();

            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 根据物料分类id返回物料
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TMaterial> GetRidById(int mid)
        {
            var list = Context.TMaterials.Where(x => x.MaterialCategoryId == mid);
            return list.ToList();
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public Model.Models.TReceivingBill GetTReceivingBillById(int rid)
        {
            var robj = Context.TReceivingBills.Find(rid);

            if (robj != null)
            {
                var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == rid).ToList();
                if (rbd != null)
                {
                    robj.BillDetailList = rbd;
                    return robj;
                }
                return robj;
            }
            return null;
        }

        /// <summary>
        /// 修改收货单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UpdReceivingBill(Model.Models.TReceivingBill m, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    var IsStatus = Context.TReceivingBills.FirstOrDefault(r => r.Id == m.Id && r.Status != 0);
                    if (IsStatus is not null || IsStatus != null)
                    {
                        message = "收货单不能再编辑,收货单号：" + IsStatus.BillNo;
                        return false;
                    }
                    message = "";
                    //供应商信息
                    var sobj = Context.TSuppliers.Find(m.SupplierId);
                    if (sobj != null)
                    {
                        m.SupplierName = sobj.Name;
                    }
                    else
                    {
                        message = "供应商不存在或已被禁用" + m.SupplierName;
                        return false;
                    }
                    var cuobj = Context.TCustomers.Find(m.CustomerId);
                    if (cuobj != null)
                    {
                        m.CustomerId = cuobj.Id;
                        m.CustomerName = cuobj.Name;
                    }
                    else
                    {
                        message = "客户不存在或已被禁用" + m.CustomerName;
                        return false;
                    }
                    //仓库信息
                    var wobj = Context.TWarehouses.Find(m.WarehouseId);
                    if (wobj != null && wobj.Status == 1)
                    {
                        m.WarehouseName = wobj.Name;
                        m.WarehouseCode = wobj.Code;
                    }
                    else
                    {
                        message = "库房不存在或已被禁用";
                        return false;
                    }


                    Context.TReceivingBills.Update(m);
                    Context.SaveChanges();
                    foreach (var item in m.BillDetailList)
                    {
                        if (item.Qty <= 0)
                        {
                            message = "数量不能小于0";
                            tran.Rollback();
                            return false;
                        }
                        if (item.Qty % 1 != 0)
                        {
                            message = "数量包含小数";
                            tran.Rollback();
                            return false;
                        }

                    }
                    var mlist = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillNo == m.BillNo && x.BillId == m.Id).ToList();
                    bool areEqual = mlist.Select(s => new { s.MaterialName, s.OwnerName, s.BatchNo }).SequenceEqual(m.BillDetailList.Select(b => new { b.MaterialName, b.OwnerName, b.BatchNo }));
                    if (areEqual)
                    {
                        foreach (var item in m.BillDetailList)
                        {
                            //foreach (var mItem in mlist)
                            //{
                            //    //if(item.Qty != mItem.Qty)
                            //    //{
                            Context.TReceivingBillDetails.Update(item);
                            Context.SaveChanges();
                            //    //}
                            //    //continue;
                            //}
                        }
                        tran.Commit();
                        return true;
                    }
                    var elementsOnlyInList1 = mlist.Except(m.BillDetailList, new ReceivingDetailsDTO());
                    var elementsOnlyInList2 = m.BillDetailList.Except(mlist, new ReceivingDetailsDTO());
                    //var differentElements = mlist.Union(m.BillDetailList, new ReceivingDetailsDTO()).Except(mlist.Intersect(m.BillDetailList, new ReceivingDetailsDTO())).Distinct(new MyClassComparer()).ToList();
                    if (elementsOnlyInList1 != null)
                    {
                        foreach (var element in elementsOnlyInList1)
                        {
                            Context.TReceivingBillDetails.Remove(element);
                            if (Context.SaveChanges() < 0)
                            {
                                message = "修改失败";
                                tran.Rollback();
                                return false;
                            }
                        }
                    }
                    if (elementsOnlyInList2 != null)
                    {
                        foreach (var element in elementsOnlyInList2)
                        {
                            if (!JudgmentBatchNo(element.BatchNo, out message))
                            {
                                message = element.MaterialName + "物料的" + message;
                                tran.Rollback();
                                return false;
                            }
                            var sub = Context.TOwners.FirstOrDefault(o => o.Status == 0 && o.Id == element.OwnerId);
                            if (sub is not null)
                            {
                                message = element.OwnerName + ",货主不存在或已被禁用";
                                tran.Rollback();
                                return false;
                            }
                            element.BillId = m.Id;
                            element.BillNo = m.BillNo;
                            element.Id = 0;
                            Context.TReceivingBillDetails.Add(element);
                            if (Context.SaveChanges() < 0)
                            {
                                message = "修改失败";
                                tran.Rollback();
                                return false;
                            }
                        }
                    }

                    #region
                    //foreach (var item in differentElements)
                    //{
                    //    if (item.Id == 0)
                    //    {
                    //        if (!JudgmentBatchNo(item.BatchNo, out message))
                    //        {
                    //            message = item.MaterialName + "物料的" + message;
                    //            tran.Rollback();
                    //            return false;
                    //        }
                    //        var sub = Context.TOwners.FirstOrDefault(o => o.Status == 0 && o.Id == item.OwnerId);
                    //        if (sub is not null)
                    //        {
                    //            message = item.OwnerName + ",货主不存在或已被禁用";
                    //            tran.Rollback();
                    //            return false;
                    //        }
                    //        item.BillId = m.Id;
                    //        item.BillNo = m.BillNo;
                    //        Context.TReceivingBillDetails.Add(item);
                    //        if (Context.SaveChanges() < 0)
                    //        {
                    //            message = "修改失败";
                    //            tran.Rollback();
                    //            return false;
                    //        }
                    //        continue;
                    //    }
                    //    var res = m.BillDetailList.FirstOrDefault(r => r.Id == item.Id);
                    //    if (res == null)
                    //    {
                    //        var data = mlist.FirstOrDefault(r => r.Id == item.Id);
                    //        if (data == null)
                    //        {
                    //             message = "修改失败";
                    //            tran.Rollback();
                    //            return false;
                    //        }
                    //        Context.TReceivingBillDetails.Remove(data);
                    //        if (Context.SaveChanges() < 0)
                    //        {
                    //            message = "修改失败";
                    //            tran.Rollback();
                    //            return false;
                    //        }
                    //        continue;
                    //    }

                    //    if (res != null)
                    //    {
                    //        if (!JudgmentBatchNo(res.BatchNo, out message))
                    //        {
                    //            message = res.MaterialName + "物料的" + message;
                    //            tran.Rollback();
                    //            return false;
                    //        }
                    //        var sub = Context.TOwners.FirstOrDefault(o => o.Status == 0 && o.Id == res.OwnerId);
                    //        if (sub is not null)
                    //        {
                    //            message = res.OwnerName + ",货主不存在或已被禁用";
                    //            tran.Rollback();
                    //            return false;
                    //        }
                    //        Context.TReceivingBillDetails.Update(res);
                    //        if (Context.SaveChanges() < 0)
                    //        {
                    //            message = "修改失败";
                    //            tran.Rollback();
                    //            return false;
                    //        }
                    //        continue;
                    //    }
                    //}
                    /*
                   #region 删除关联的订单明细
                   if (mlist != null)
                   {
                       Context.RemoveRange(mlist);
                       Context.SaveChanges();
                   }
                   #endregion


                   foreach (var item in m.BillDetailList)
                   {
                       if (!JudgmentBatchNo(item.BatchNo, out message))
                       {
                           message = item.MaterialName + "物料的" + message;
                           tran.Rollback();
                           return false;
                       }
                       var sub = Context.TOwners.FirstOrDefault(o => o.Status == 0 && o.Id == item.OwnerId);
                       if (sub is not null)
                       {
                           message = item.OwnerName + ",货主不存在或已被禁用";
                           tran.Rollback();
                           return false;
                       }
                       item.Id = 0;
                       item.BillId = m.Id;
                       //关联单号
                       item.BillNo = m.BillNo;
                       //初始化状态
                       item.Status = 0;
                       //创建日期
                       item.CreateDate = DateTime.Now;
                       Context.TReceivingBillDetails.Add(item);
                   }
                   */
                    #endregion

                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdReceivingBillStatus(int rid)
        {
            var robj = Context.TReceivingBills.Find(rid);
            if (robj != null)
            {
                robj.Status = 2;
                Context.TReceivingBills.Update(robj);
                Context.SaveChanges();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 添加入库单的方法仅本类使用
        /// </summary>
        /// <param name="m"></param>
        /// <param name="receordercode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool AddReceivingOrderDeatils(ReceivingBillOrderDto m, string receordercode, out string message, ref List<TCell> Getcell)
        {
            message = "";
            bool reresult = false;
            foreach (var item in m.ReceivingBillOrderDetailDtos)
            {

                TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                #region 蒙牛详细批次西安暂时弃用
                //if (item.SmallBatchNo == null || item.SmallBatchNo == "" || item.SmallBatchNo.Length <= 11)
                //{
                //    if (!reresult)
                //    {
                //        message = "详细批次有误";
                //        reresult = false;
                //    }
                //    continue;
                //}
                //var recevingorder = Context.TReceivingOrderDetails.FirstOrDefault(r => r.SmallBatchNo == item.SmallBatchNo);
                //if (recevingorder is not null)
                //{
                //    message = "有相同的详细批次";
                //    return false;
                //}
                #endregion
                if (item.ReceivedQty == 0 || (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode) || string.IsNullOrEmpty(item.PalletBarcode) ))
                {
                    if (!reresult)
                    {
                        message = "收货数量或托盘或批次有误";
                        reresult = false;
                    }
                    continue;
                }

                //item.SmallBatchNo = Regex.Replace(item.SmallBatchNo, "(^|-)([a-z])", match => match.Groups[1].Value + match.Groups[2].Value.ToUpperInvariant());
                message = "";
                receivingOrder.OrderSn = receordercode;
                //本地入库
                receivingOrder.BillType = 1;
                receivingOrder.WarehouseId = m.Wid;
                receivingOrder.SupplierId = m.Suppid;
                receivingOrder.MaterialId = item.MaterialId;
                receivingOrder.OwnerId = item.OwerId;
                receivingOrder.BatchNo = item.MaterialBatchNo;
                receivingOrder.SmallBatchNo = item.SmallBatchNo;
                receivingOrder.CustomerId = m.CustomerId;
                //订单来源默认手动创建
                receivingOrder.SourceType = 0;
                //质检状态默认为合格
                receivingOrder.QualityState = 1;
                //质量状态
                receivingOrder.Status = 3;
                receivingOrder.ReceivedQty = 0;
                receivingOrder.PackagedQty = 0;
                receivingOrder.PackQty = 0;
                receivingOrder.BatchNoExplain = item.BatchNoExplain;
                receivingOrder.OutFactoryDate = item.OutFactoryDate;
                receivingOrder.ProduceFactory = item.ProduceFactory;
                receivingOrder.ProductDate = item.ProductDate;
                receivingOrder.PalletBarcode = item.PalletBarcode;
                receivingOrder.ExpireDate = item.ExpireDate;
                receivingOrder.Remark = item.Remark;
                receivingOrder.Qty = item.ReceivedQty;
                receivingOrder.Weight = item.Weight == null ? 0 : (decimal)item.Weight;
                receivingOrder.DateBackToOrderSn = item.DateBackToOrderSn;
                #region 审计字段
                receivingOrder.CreateUserId = m.NowUserId;
                receivingOrder.CreateUserName = m.NowUserRealName;
                receivingOrder.CreateDate = DateTime.Now;
                //receivingOrder.ModifyUserId = m.NowUserId;
                //receivingOrder.ModifyUserName = m.NowUserRealName;
                //receivingOrder.ModifyDate = DateTime.Now;
                receivingOrder.AuditUserId = m.NowUserId;
                receivingOrder.AuditUserName = m.NowUserRealName;
                receivingOrder.AuditDate = DateTime.Now;
                receivingOrder.SubmitUserId = m.NowUserId;
                receivingOrder.SubmitUserName = m.NowUserRealName;
                receivingOrder.SubmitDate = DateTime.Now;
                receivingOrder.ReceivingBillId = m.Id;
                #endregion
                //采购订单行项目类型
                receivingOrder.PurOrderLineType = 0;
                receivingOrder.StackedQty = 0;
                reresult = AddTReceivingOrderDetail(receivingOrder, out message);
                if (reresult == false)
                {
                    message = "添加入库单失败" + message;
                    return false;
                }
                var receiving = Context.TReceivingOrderDetails.First(r => r.Id == receivingOrder.Id);
                PalletTallyInputModel palletTallyInputModel = new PalletTallyInputModel();
                palletTallyInputModel.PalletBarcode = item.PalletBarcode;
                palletTallyInputModel.TotalNum = item.ReceivedQty;
                palletTallyInputModel.OrderDetailId = receiving.Id;
                palletTallyInputModel.WarehouseId = receiving.WarehouseId;
                palletTallyInputModel.LogicPartCode = receiving.LogicalPartCode;
                palletTallyInputModel.PalletPackage.MaterialCode = receiving.MaterialCode;
                reresult = StackingStorageService.BuildCreateStackingStorageEF(out message, palletTallyInputModel, ref Getcell);
                if (!reresult)
                {
                    if (message is null || message == "")
                    {
                        message = "保存组箱数据失败";
                    }
                    else
                    {
                        message = message;
                    }
                    return false;
                }
            }
            return reresult;
        }

        /// <summary>
        /// 入库任务下传
        /// </summary>
        /// <param name="sList"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool ReceivingTaskDownload(List<ShelvesSinles> sList, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    message = "";
                    foreach (var shelves in sList)
                    {
                        #region 许佳杰代码
                        //var receivingBillDetail = new TReceivingBillDetail();
                        //var receivingBill = Context.TReceivingBills.FirstOrDefault(x => x.BillNo == shelves.Id);
                        //var s = sList.Where(x => x.Id == shelves.Id);
                        //if (receivingBill != null || s.Count() > 1)
                        //{
                        //    receivingBillDetail.BillId = receivingBill.Id;
                        //    receivingBillDetail.BillNo = receivingBill.BillNo;
                        //    receivingBillDetail.BillLineNo = shelves.ShelvesNo;
                        //    receivingBillDetail.MaterialCode = shelves.MaterialNo;
                        //    receivingBillDetail.MaterialName = shelves.MaterialDesc;
                        //    receivingBillDetail.MaterialDesc = shelves.MaterialDesc;
                        //    receivingBillDetail.Qty = shelves.ShelvesQuantity;
                        //    receivingBillDetail.ReceivedQty = 0;
                        //    receivingBillDetail.Status = 0;
                        //    receivingBillDetail.CreateDate = Convert.ToDateTime(shelves.CreateTime);
                        //    receivingBillDetail.SupplierName = shelves.SupplierName;
                        //    receivingBillDetail.BatchNo = shelves.BatchNo;
                        //    receivingBillDetail.ProduceFactory = shelves.Factory;
                        //    receivingBillDetail.SerialnoParam = shelves.SerialnoParam;
                        //    if (shelves.SerialnoParam == "启用")
                        //    {
                        //        foreach (var batchSerial in shelves.BatchSerial)
                        //        {
                        //            receivingBillDetail.MaterialSerializeId = batchSerial.Id;
                        //            receivingBillDetail.MaterialSerialize = batchSerial.MaterialSerialize;
                        //            receivingBillDetail.MaterialSerializeBatchNo = batchSerial.BatchNo;
                        //        }
                        //    }
                        //    //receivingBillDetails.Add(receivingBillDetail);
                        //    Context.TReceivingBillDetails.Add(receivingBillDetail);
                        //    continue;
                        //}
                        #endregion
                        var r = new TReceivingBill();
                        r.OrderId = shelves.Id;
                        r.ShelvesNo = shelves.ShelvesNo;
                        r.BaseUnit = shelves.BaseUnit;
                        r.BillNo = shelves.ShelvesNo;
                        r.SupplierName = shelves.SupplierName;
                        r.Status = 0;
                        r.CreateDate = Convert.ToDateTime(shelves.CreateTime);
                        r.StoLocation = shelves.StockLocation;
                        //总数量
                        r.TotalQty = shelves.BaseQuantity;
                        r.CreateUserName = shelves.Founder;
                        r.OrderUnit = shelves.OrderUnit;
                        r.NoticeNo = shelves.NoticeNo;
                        r.NoticeLineNo = shelves.NoticeLineNo;
                        r.Workers = shelves.Workers;
                        r.StorageArea = shelves.StorageArea;
                        r.BinNo = shelves.BinNo;
                        r.WarehouseId = 2;
                        Context.TReceivingBills.Add(r);
                        Context.SaveChanges();
                        var receivingBillDetail = new TReceivingBillDetail();
                        receivingBillDetail.BillId = r.Id;
                        receivingBillDetail.BillNo = r.BillNo;
                        //receivingBillDetail.BillLineNo = shelves.ShelvesNo;
                        receivingBillDetail.MaterialCode = shelves.MaterialNo;
                        receivingBillDetail.MaterialName = shelves.MaterialDesc;
                        var materobj = Context.TMaterial.AsNoTracking().FirstOrDefault(x => x.Code == shelves.MaterialNo);
                        if (materobj != null)
                        {
                            receivingBillDetail.MaterialId = materobj.Id;
                        }
                        else
                        {
                            TMaterial material = new TMaterial();
                            material.Code = shelves.MaterialNo;
                            material.Name = shelves.MaterialDesc;
                            material.CreateDate = DateTime.Now;
                            Context.TMaterial.Add(material);
                            Context.SaveChanges();
                            receivingBillDetail.MaterialId = material.Id;
                        }
                        if (shelves.BatchSerial.Any())
                        {
                            foreach (var item in shelves.BatchSerial)
                            {
                                receivingBillDetail.MaterialSerialize = item.MaterialSerialize;
                            }
                        }
                        receivingBillDetail.Qty = shelves.ShelvesQuantity;
                        receivingBillDetail.ReceivedQty = 0;
                        receivingBillDetail.Status = 0;
                        receivingBillDetail.CreateDate = Convert.ToDateTime(shelves.CreateTime);
                        receivingBillDetail.SupplierName = shelves.SupplierName;
                        receivingBillDetail.BatchNo = shelves.BatchNo;
                        receivingBillDetail.ProduceFactory = shelves.Factory;
                        receivingBillDetail.SerialnoParam = shelves.SerialnoParam;
                        Context.TReceivingBillDetails.Add(receivingBillDetail);
                    }

                    //提交保存
                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                    tran.Rollback();
                    return false;
                    throw;
                }
            }
        }

        /// <summary>
        /// 获取提交入库的数据
        /// </summary>
        /// <returns></returns>
        public List<ShelvesSinles> GetSubmitOutList()
        {
            List<ShelvesSinles> slist = new List<ShelvesSinles>();
            var rlist = Context.TReceivingBills.Where(x => x.Status == 2).AsNoTracking().OrderBy(r => r.CreateDate).ToList();
            if (rlist.Any())
            {

                foreach (var item in rlist)
                {
                    ShelvesSinles sobj = new ShelvesSinles();
                    sobj.Id = item.OrderId;
                    sobj.ShelvesNo = item.ShelvesNo;
                    sobj.BaseUnit = item.BaseUnit;
                    sobj.SupplierName = item.SupplierName;
                    sobj.CreateTime = item.CreateDate.ToString();
                    sobj.StockLocation = item.StoLocation;
                    sobj.BaseQuantity = item.TotalQty == null ? 0 : (decimal)item.TotalQty;
                    sobj.Founder = item.CreateUserName;
                    sobj.OrderUnit = item.OrderUnit;
                    sobj.NoticeNo = item.NoticeNo;
                    sobj.NoticeLineNo = item.NoticeLineNo;
                    sobj.Workers = item.Workers;
                    sobj.StorageArea = item.StorageArea;
                    sobj.BinNo = item.BinNo;
                    var revbilldelist = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == item.Id);
                    if (revbilldelist.Any())
                    {
                        foreach (var item2 in revbilldelist)
                        {
                            BatchSerials bserobj = new BatchSerials();
                            //sobj.ShelvesNo = item2.BillLineNo;
                            sobj.MaterialNo = item2.MaterialCode;
                            sobj.MaterialDesc = item2.MaterialName;
                            sobj.ShelvesQuantity = item2.Qty;
                            sobj.CreateTime = item2.CreateDate.ToString();
                            sobj.SupplierName = item2.SupplierName;
                            sobj.BatchNo = item2.BatchNo;
                            sobj.Factory = item2.ProduceFactory;
                            sobj.SerialnoParam = item2.SerialnoParam;
                            bserobj.MaterialSerialize = item2.MaterialSerialize;
                            sobj.BatchSerial.Add(bserobj);
                        }
                    }

                    slist.Add(sobj);
                    #region 暂时弃用
                    //var rbds = Context.TReceivingBillDetails.Where(x => x.BillNo == reces.BillNo).AsNoTracking().ToList();
                    //foreach (var item2 in rbds)
                    //{
                    //    List<BatchSerials> bList = new List<BatchSerials>();
                    //    foreach (var b in bList)
                    //    {
                    //        b.Id = item2.MaterialSerializeId;
                    //        b.MaterialSerialize = item2.MaterialSerialize;
                    //        b.BatchNo = item2.MaterialSerializeBatchNo;
                    //        bList.Add(b);
                    //    }
                    //    ShelvesSinles data = new ShelvesSinles()
                    //    {
                    //        Id = reces.BillNo,
                    //        StockLocation = reces.StoLocation,
                    //        SupplierName = reces.SupplierName,
                    //        CreateTime = Convert.ToString(reces.CreateDate),
                    //        BaseQuantity = Convert.ToDecimal(reces.TotalQty),
                    //        Founder = reces.CreateUserName,
                    //        OrderUnit = reces.OrderUnit,
                    //        NoticeNo = reces.NoticeNo,
                    //        NoticeLineNo = reces.NoticeLineNo,
                    //        Workers = reces.Workers,
                    //        ShelvesNo = item2.BillLineNo,
                    //        MaterialNo = item2.MaterialCode,
                    //        MaterialDesc = item2.MaterialName,
                    //        BatchNo = item2.BatchNo,
                    //        Factory = item2.ProduceFactory,
                    //        SerialnoParam = item2.SerialnoParam,
                    //        BatchSerial = bList,

                    //        //仓位
                    //        BinNo = item.LocationCode,
                    //        StorageArea = item.StorageArea,
                    //        ShelvesQuantity = item2.Qty,
                    //    };
                    //    slist.Add(data);
                    //}
                    #endregion
                }
            }


            return slist;
        }


        /// <summary>
        /// 根据业务类型查询AGV路线
        /// </summary>
        /// <param name="BillType"></param>
        /// <returns></returns>
        public AGVRequestDto GetAGVMessageByBillType(out string message, string AGVStartPoint, int BillType)
        {
            message = "";
            AGVRequestDto AGVRequestDto = new AGVRequestDto();

            var agvBindDingPoint = Context.TAGVBinDingPoint.Where(x => x.TaskType == BillType);
            if (agvBindDingPoint.Count() <= 0)
            {
                message = "暂未查询到申请的业务类型，请检查是否维护AGV点位表";
                return null;
            }

            AGVRequestDto.fromSide = AGVStartPoint;
            AGVRequestDto.toSide = agvBindDingPoint.First().AGVEndPoint;
            AGVRequestDto.agvGroup = agvBindDingPoint.First().AGVGroup;
            AGVRequestDto.AGVFloor = agvBindDingPoint.First().AGVFloor;
            return AGVRequestDto;
        }


        /// <summary>
        /// 根据业务类型查询AGV路线
        /// </summary>
        /// <param name="BillType"></param>
        /// <returns></returns>
        public AGVRequestDto GetAGVMessageByBillTypeOut(out string message, string AGVEndPoint, int BillType)
        {
            message = "";
            AGVRequestDto AGVRequestDto = new AGVRequestDto();

            var agvBindDingPoint = Context.TAGVBinDingPoint.Where(x => x.TaskType == BillType);
            if (agvBindDingPoint.Count() <= 0)
            {
                message = "暂未查询到申请的业务类型，请检查是否维护AGV点位表";
                return null;
            }

            AGVRequestDto.fromSide = agvBindDingPoint.First().AGVStartPoint;
            AGVRequestDto.toSide = AGVEndPoint;
            AGVRequestDto.agvGroup = agvBindDingPoint.First().AGVGroup;
            AGVRequestDto.AGVFloor = agvBindDingPoint.First().AGVFloor;
            return AGVRequestDto;
        }


        public TaskLiku GetWCSMessageByMaterial(out string msg, string materialCode, string PallBarcode)
        {
            msg = "";
            TaskLiku taskLiku = new TaskLiku();

            var inventoryList = Context.TInventory.Where(x => x.MaterialCode == materialCode && x.PalletBarcode == PallBarcode);
            if (inventoryList.Count() <= 0)
            {
                msg = "未查询到库存信息";
                return null;
            }
            if (inventoryList.First().LocationCode == null || inventoryList.First().LocationCode == "")
            {
                msg = "物料" + inventoryList.First().MaterialName + "暂无仓位信息";
                return null;
            }
            taskLiku.taskSubType = "102";
            taskLiku.startPositionId = inventoryList.First().LocationCode;
            taskLiku.endPositionId = "string";
            taskLiku.palletCode = PallBarcode;
            taskLiku.type = 1;

            return taskLiku;
        }

        public TAGVBinDingPoint GetAGVPoint(int taskType, out string message)
        {
            message = "";
            var list = Context.TAGVBinDingPoint.FirstOrDefault(x => x.TaskType == taskType);
            if (list == null)
            {
                message = "暂无此业务类型的AGV点位信息";
                return null;
            }
            return list;
        }

        public bool UpAGVPonitMessage(int taskType, string point, out string message)
        {
            message = "";
            var list = Context.TAGVBinDingPoint.FirstOrDefault(x => x.TaskType == taskType);
            if (list == null)
            {
                message = "暂无此业务类型";
                return false;
            }
            list.AGVStartPoint = point;
            Context.TAGVBinDingPoint.Update(list);
            if(Context.SaveChanges() <= 0)
            {
                message = "更新点位失败";
                return false;
            }
            return true;

        }

    }
}
